<?php


define('API_KEY',"f3985f3e812a3952e492b72f219ebdb4");


$stocks = array(
    "600686",
    "600891"
);

$Stock = new Stock();
$Stock->view($stocks);


class Stock {

    function view($stocks){
        if(!empty($stocks)){
            foreach($stocks as $key => $stock){
                if($stock < "600000"){
                    $stocks[$key] = "sz".$stock;
                }else{
                    $stocks[$key] = "sh".$stock;
                }
            }
        }
        $params = array(
            "apikey" => API_KEY,
            "stockid" => implode(",",$stocks),
            "list" => 1
        );
        $result = $this->callAPI("http://apis.baidu.com/apistore/stockservice/hkstock",$params);
        if($result['retData']['stockinfo']){
            foreach($result['retData']['stockinfo'] as $stockInfo){
                echo $stockInfo['code'] ." ".$stockInfo['currentPrice'];
            }
        }
    }
    function callAPI($url,$params){

        $ch = curl_init();
        $url .= '?'.http_build_query($params);
        $header = array(
            'apikey: '.API_KEY,
        );
        // 添加apikey到header
        curl_setopt($ch, CURLOPT_HTTPHEADER  , $header);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // 执行HTTP请求
        curl_setopt($ch , CURLOPT_URL , $url);
        $res = curl_exec($ch);

        return json_decode($res,true);
    }
}